export function addListReturnRemove(item, list) {
  list.push(item);
  return () => {
    if (Array.isArray(list)) {
      for (let i = 0; i < list.length; ++i) {
        if (item === list[i]) {
          list.slice(i);
          break;
        }
      }
    }
  };
}

export function promisify(api) {
  return (options, ...params) => {
    return new Promise((resolve, reject) => {
      api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
    });
  };
}

export async function sleep(duration) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, duration);
  });
}



export function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
    return ("00" + bit.toString(16)).slice(-2);
  });
  return hexArr.join("");
}

export function hex2ab(hex) {
  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
      return parseInt(h, 16);
  }));
  return typedArray.buffer;
}

export function buffer2Str(buffer) {
  let hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
    return ("00" + bit.toString(16)).slice(-2);
  });
  return `${hexArr[0]}:${hexArr[1]}:${hexArr[2]}:${hexArr[3]}:${hexArr[4]}:${hexArr[5]}`
    .toUpperCase();
}

export function str2ab(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str[i];
  }
  return buf;
}

export function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

export function str2Bytes(str) {
  return str.map(function(x) {
    return x.charCodeAt(0);
  });
}


/**
 * platfrom 相关
 */

// 判断是不是 Android
export function isAndroid() {
  var isAndroid = /(android)/i.test(navigator.userAgent);
  return isAndroid;
}

// 判断是不是 IOS9
export function isIOS() {
  var isIOS = /(iphone|ipad|ipod)/i.test(navigator.userAgent);
  return isIOS;
}

export function isWxApp() {
  var isWxApp = typeof wx === "object" && typeof getAPP === "function";
  return isWxApp;
}


export function getQueryString(name) {
  if (typeof location !== "object") {
    return null;
  }
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null)
      return decodeURI(r[2]);
  return null;
}